package com.xl6667.filter;

import com.alibaba.fastjson.JSON;
import com.xl6667.constants.RedisConstants;
import com.xl6667.domain.ResponseResult;
import com.xl6667.domain.entity.LoginUser;
import com.xl6667.enums.AppHttpCodeEnum;
import com.xl6667.util.JwtUtil;
import com.xl6667.util.RedisCache;
import com.xl6667.util.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * jwt验证
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (Objects.isNull(token)){
            //为空直接放行，无需登录
            filterChain.doFilter(request,response);
            return;
        }
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //令牌过期重新登录
            e.printStackTrace();
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        //获取用户id
        String id = claims.getSubject();
        //从redis中获取用户信息
        LoginUser loginUser = (LoginUser) redisCache.getCacheObject("blogLogin" + id);
        if(Objects.isNull( loginUser )){
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        //更新redis中token过期时间
        redisCache.setCacheObject("blogLogin"+id,loginUser, RedisConstants.LOGIN_CACHE_TIME, TimeUnit.HOURS);
        //将用户信息存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
